package net.m510.autosurfer.core;

import java.io.IOException;
import java.util.logging.Logger;

import net.m510.autosurfer.core.utils.AnalyzeUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


public class DocumentResponseHandler implements ResponseHandler<Document> {
	private static final Logger log = Logger.getLogger(DocumentResponseHandler.class.getName());
	public static String DEFAULT_CHARSET="UTF-8";
	private String defaultCharset = DEFAULT_CHARSET;
	private String actualCharset;
	
	public DocumentResponseHandler() {
		super();
	}
	public DocumentResponseHandler(String defaultCharset) {
		super();
		this.defaultCharset = defaultCharset;
	}
	
	@Override
	public Document handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		HttpEntity entity = response.getEntity();
		String charset = AnalyzeUtils.getCharset(response,defaultCharset);
		Document doc = Jsoup.parse(EntityUtils.toString(entity,charset));
		actualCharset = AnalyzeUtils.getCharset(entity,charset);
		log.fine("charset encoding(maybe)="+actualCharset);
		EntityUtils.consume(entity);
		return doc;
	}
	
	public String getDefaultCharset() {
		return defaultCharset;
	}
	public void setDefaultCharset(String charset) {
		this.defaultCharset = charset;
	}
	public String getActualCharset() {
		return actualCharset;
	}
}
